<template>
  <view class="audit-list-container">
    <!-- 分类标签栏 -->
    <view class="category-tabs">
      <view
        class="tab-item"
        :class="{ active: currentCategory === 'member' }"
        @click="switchCategory('member')"
      >
        会员审核
      </view>
      <view
        class="tab-item"
        :class="{ active: currentCategory === 'clan' }"
        @click="switchCategory('clan')"
      >
        宗亲荟成员审核
      </view>
    </view>

    <!-- 顶部筛选栏 -->
    <view class="filter-bar">
      <picker mode="selector" :range="statusOptions" range-key="label" @change="statusChange">
        <view class="filter-item">
          {{ currentStatus.label }}
          <uni-icons type="arrowdown" size="14" color="#666"></uni-icons>
        </view>
      </picker>

      <picker mode="date" fields="month" @change="dateChange">
        <view class="filter-item">
          {{ currentDate || "选择月份" }}
          <uni-icons type="calendar" size="14" color="#666"></uni-icons>
        </view>
      </picker>
    </view>

    <!-- 列表内容 -->
    <scroll-view
      scroll-y
      class="list-scroll"
      refresher-enabled
      :refresher-triggered="refreshing"
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
    >
      <!-- 会员审核数据 -->
      <template v-if="currentCategory === 'member'">
        <view
          v-if="memberList.length === 0 && !memberLoading && !initialLoading"
          class="empty-state"
        >
          <image src="/static/images/empty.png" mode="aspectFit"></image>
          <text>暂无会员审核数据</text>
        </view>

        <view v-if="initialLoading" class="initial-loading">
          <text>加载中...</text>
        </view>

        <view v-for="(item, index) in memberList" :key="'member-' + index" class="list-item">
          <view class="item-header">
            <text class="item-title">{{ item.username || "未知家族" }}</text>
            <text :class="['status-tag', getStatusClass(item.status)]">
              {{ getStatusText(item.status) }}
            </text>
          </view>
          <view class="item-content">
            <view>
              <text class="item-desc">{{ item.nickname || "无" }}</text>
              <view class="item-meta">
                <text>{{ item.createTime || "" }}</text>
              </view>
            </view>
            <view class="item-actions">
              <button
                v-if="item.status === 0"
                class="action-btn pass"
                @click="handleAudit(item.id, item.familyId, 'pass')"
              >
                审核
              </button>
            </view>
          </view>
        </view>

        <!-- <view v-if="memberLoading" class="loading-more">
          <text>加载中...</text>
        </view> -->
        <view v-if="memberNoMore && memberList.length > 0" class="no-more">
          <text>没有更多数据了</text>
        </view>
      </template>

      <!-- 宗亲荟成员审核数据 -->
      <template v-if="currentCategory === 'clan'">
        <view v-if="clanList.length === 0 && !clanLoading && !initialLoading" class="empty-state">
          <image src="/static/images/empty.png" mode="aspectFit"></image>
          <text>暂无宗亲荟成员审核数据</text>
        </view>

        <view v-if="initialLoading" class="initial-loading">
          <text>加载中...</text>
        </view>

        <view
          v-for="(item, index) in clanList"
          :key="'clan-' + index"
          class="list-item clan-member-item"
        >
          <view class="item-content">
            <view class="item-avatar">
              <image
                :src="item.photoUrl || item.photoUrl || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/fa6cbef09f834c41b7121841f6a9564e.png'"
                mode="aspectFill"
                class="avatar-img"
              ></image>
            </view>
            <view class="item-content-wrapper">
              <view class="item-header">
                <view class="user-info">
                  <text class="user-name">{{ item.name || "未知姓名" }}</text>
                  <!-- <text v-if="item.jobTitle || item.position" class="job-title">{{ item.jobTitle || item.position
                  }}</text> -->
                </view>
                <text :class="['status-tag', getStatusClass(item.status)]">
                  {{ getStatusText(item.status) }}
                </text>
              </view>
              <view v-if="item.positionList.length" class="position-info">
                <view v-if="item.positionList && item.positionList.length" class="position-tags">
                  <text v-for="(pos, idx) in item.positionList" :key="idx" class="position-tag">
                    {{ pos.name }}
                  </text>
                </view>
                <text v-else>{{ item.position || "暂无职位" }}</text>
              </view>
              <view class="company-info">
                <text class="company-name">{{ item.companyName }}</text>
                <text class="company-position">- {{ item.companyPosition || "暂未职位" }}</text>
              </view>
            </view>
          </view>
          <view class="item-actions">
            <view class="item-meta">
              <text class="add-time">{{ item.createTime }}</text>
            </view>
            <button
              v-if="item.status === 0"
              class="action-btn pass"
              @click="
                handleClanAudit(item.id, item.familyId || item.clanId || item.clanFamilyId, 'pass')
              "
            >
              审核
            </button>
            <!-- <button v-else class="action-btn detail"
              @click="handleAudit(item.id, item.familyId || item.clanId || item.clanFamilyId, 'view')">查看详情</button> -->
          </view>
        </view>

        <view v-if="clanLoading" class="loading-more">
          <text>加载中...</text>
        </view>
        <view v-if="clanNoMore && clanList.length > 0" class="no-more">
          <text>没有更多数据了</text>
        </view>
      </template>
    </scroll-view>
  </view>
</template>
<script>
import getApiProcess from "@/api/genealogy/family-user.ts";
import ClanMember from "@/api/genealogy/clanMember.ts";
const userInfo = uni.getStorageSync("user-info");
export default {
  data() {
    return {
      // 分类切换
      currentCategory: "member", // 默认选中会员审核

      // 筛选条件
      statusOptions: [
        { label: "全部状态", value: "all" },
        { label: "待审核", value: "0" },
        { label: "已通过", value: "1" },
        { label: "已拒绝", value: "2" },
      ],
      currentStatus: { label: "全部状态", value: "all" },
      currentDate: "",

      // 分页参数 - 会员审核
      memberPageNum: 1,
      memberPageSize: 10,
      memberList: [],
      memberLoading: false,
      memberNoMore: false,

      // 分页参数 - 宗亲荟成员审核
      clanPageNum: 1,
      clanPageSize: 10,
      clanList: [],
      clanLoading: false,
      clanNoMore: false,

      // 筛选参数
      filterParams: {},
      refreshing: false, // 新增：控制下拉刷新状态
      initialLoading: true, // 新增：控制首次加载状态
      loadError: false, // 新增：控制加载错误状态
    };
  },
  onLoad(options) {
    this.loadData();
  },
  methods: {
    // 切换分类
    switchCategory(category) {
      if (this.currentCategory === category) return;
      this.currentCategory = category;
      this.resetPagination();
      this.loadData();
    },

    // 根据当前分类加载数据
    loadData(isLoadMore = false) {
      if (this.currentCategory === "member") {
        this.getMemberList(isLoadMore);
      } else {
        this.getClanList(isLoadMore);
      }
    },

    // 获取会员审核列表
    getMemberList(isLoadMore = false) {
      if (this.memberLoading) return;

      this.memberLoading = true;
      this.loadError = false;

      const params = {
        pageNum: this.memberPageNum,
        pageSize: this.memberPageSize,
        familyId: userInfo.userFamilyId,
        ...this.filterParams,
      };

      if (this.currentStatus.value !== "all") {
        params.status = this.currentStatus.value;
      }

      if (this.currentDate) {
        params.createTime = this.currentDate;
      }

      getApiProcess
        .getProcess(params)
        .then((data) => {
          if (isLoadMore) {
            this.memberList = [...this.memberList, ...data.list];
          } else {
            this.memberList = data.list.reverse();
          }

          if (data.list && data.list.length < this.memberPageSize) {
            this.memberNoMore = true;
          } else {
            this.memberNoMore = false;
          }
        })
        .catch((error) => {
          console.error("获取会员审核数据失败:", error);
          this.loadError = true;
          uni.showToast({
            title: "获取会员审核数据失败",
            icon: "none",
          });
        })
        .finally(() => {
          this.memberLoading = false;
          if (this.refreshing) {
            this.refreshing = false;
          }
          this.initialLoading = false;
        });
    },

    // 获取宗亲荟成员审核列表
    getClanList(isLoadMore = false) {
      if (this.clanLoading) return;

      this.clanLoading = true;
      this.loadError = false;

      const params = {
        pageNum: this.clanPageNum,
        pageSize: this.clanPageSize,
        familyId: userInfo.userFamilyId,
        ...this.filterParams,
      };

      if (this.currentStatus.value !== "all") {
        params.status = this.currentStatus.value;
      }

      if (this.currentDate) {
        params.createTime = this.currentDate;
      }

      ClanMember.getClanMemberList(params)
        .then((data) => {
          console.log(data, 12222222222222);
          if (isLoadMore) {
            this.clanList = [...this.clanList, ...data.list];
          } else {
            this.clanList = data.list.reverse();
          }

          if (data.list && data.list.length < this.clanPageSize) {
            this.clanNoMore = true;
          } else {
            this.clanNoMore = false;
          }
        })
        .catch((error) => {
          console.error("获取宗亲荟成员审核数据失败:", error);
          this.loadError = true;
          uni.showToast({
            title: "获取宗亲荟成员审核数据失败",
            icon: "none",
          });
        })
        .finally(() => {
          this.clanLoading = false;
          if (this.refreshing) {
            this.refreshing = false;
          }
          this.initialLoading = false;
        });
    },

    // 重置分页参数
    resetPagination() {
      this.memberPageNum = 1;
      this.memberNoMore = false;
      this.memberList = [];

      this.clanPageNum = 1;
      this.clanNoMore = false;
      this.clanList = [];
    },

    getStatusText(status) {
      const map = {
        0: "待审核",
        1: "已通过",
        2: "已拒绝",
      };
      return map[status] || "未知状态";
    },
    getStatusClass(status) {
      return `status-${status}`;
    },
    statusChange(e) {
      this.currentStatus = this.statusOptions[e.detail.value];
      this.resetPagination();
      this.loadData();
    },
    dateChange(e) {
      this.currentDate = e.detail.value;
      this.resetPagination();
      this.loadData();
    },
    handleAudit(id, familyId, action) {
      uni.navigateTo({
        url: `/pages/mine/process/familyTree/index?personId=${id}&familyId=${familyId}`,
      });
    },
    // 审核宗亲荟成员信息
    handleClanAudit(id, familyId, action) {
      console.log(id, familyId);
      // 创建自定义审核弹出框
      this.showCustomAuditModal(id, familyId);
    },

    // 显示自定义审核弹出框
    showCustomAuditModal(id, familyId) {
      // 使用自定义组件或创建DOM元素
      const modal = document.createElement("div");
      modal.innerHTML = `
        <div class="custom-modal-overlay" id="auditModalOverlay">
          <div class="custom-modal">
            <div class="modal-header">
              <h3>审核确认</h3>
              <span class="close-btn" onclick="closeAuditModal()">×</span>
            </div>
            <div class="modal-content">
              <p>请确认是否通过该宗亲荟成员的审核申请？</p>
            </div>
            <div class="modal-footer">
              <button class="btn btn-pass" onclick="handleAuditPass('${id}', '${familyId}')">通过</button>
              <button class="btn btn-reject" onclick="handleAuditReject('${id}', '${familyId}')">拒绝</button>
              <button class="btn btn-cancel" onclick="closeAuditModal()">取消</button>
            </div>
          </div>
        </div>
      `;

      // 添加样式
      const style = document.createElement("style");
      style.textContent = `
        .custom-modal-overlay {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          z-index: 9999;
        }
        .custom-modal {
          background: white;
          border-radius: 8px;
          width: 80%;
          max-width: 300px;
          padding: 20px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          border-bottom: 1px solid #eee;
          padding-bottom: 10px;
        }
        .modal-header h3 {
          margin: 0;
          font-size: 18px;
          color: #333;
        }
        .close-btn {
          font-size: 24px;
          cursor: pointer;
          color: #999;
          line-height: 1;
        }
        .close-btn:hover {
          color: #666;
        }
        .modal-content {
          margin-bottom: 20px;
        }
        .modal-content p {
          margin: 0;
          font-size: 16px;
          color: #666;
          line-height: 1.5;
        }
        .modal-footer {
          display: flex;
          gap: 10px;
          justify-content: flex-end;
        }
        .btn {
          padding: 8px 16px;
          border: none;
          border-radius: 4px;
          font-size: 14px;
          cursor: pointer;
          transition: background-color 0.3s;
        }
        .btn-pass {
          background-color: #07c160;
          color: white;
        }
        .btn-reject {
          background-color: #ff4d4f;
          color: white;
        }
        .btn-cancel {
          background-color: #f0f0f0;
          color: #666;
        }
      `;

      // 添加全局函数
      window.closeAuditModal = () => {
        const overlay = document.getElementById("auditModalOverlay");
        if (overlay) {
          overlay.remove();
        }
      };

      window.handleAuditPass = (id, familyId) => {
        this.processClanAudit(id, familyId, 1, "审核通过");
        closeAuditModal();
      };

      window.handleAuditReject = (id, familyId) => {
        this.showRejectModal(id, familyId);
        closeAuditModal();
      };

      // 点击蒙板关闭
      modal.onclick = (e) => {
        if (e.target.id === "auditModalOverlay") {
          closeAuditModal();
        }
      };

      document.head.appendChild(style);
      document.body.appendChild(modal);
    },

    // 显示拒绝原因弹出框
    showRejectModal(id, familyId) {
      const modal = document.createElement("div");
      modal.innerHTML = `
        <div class="custom-modal-overlay" id="rejectModalOverlay">
          <div class="custom-modal">
            <div class="modal-header">
              <h3>拒绝原因</h3>
              <span class="close-btn" onclick="closeRejectModal()">×</span>
            </div>
            <div class="modal-content">
              <p>请输入拒绝原因（选填）</p>
              <textarea id="rejectReason" placeholder="请输入拒绝原因..." rows="3" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-top: 10px; font-size: 14px;"></textarea>
            </div>
            <div class="modal-footer">
              <button class="btn btn-reject" onclick="confirmReject('${id}', '${familyId}')">确认拒绝</button>
              <button class="btn btn-cancel" onclick="closeRejectModal()">取消</button>
            </div>
          </div>
        </div>
      `;

      // 添加全局函数
      window.closeRejectModal = () => {
        const overlay = document.getElementById("rejectModalOverlay");
        if (overlay) {
          overlay.remove();
        }
      };

      window.confirmReject = (id, familyId) => {
        const reason = document.getElementById("rejectReason").value || "不符合宗亲荟成员要求";
        this.processClanAudit(id, familyId, 0, reason);
        closeRejectModal();
      };

      // 点击蒙板关闭
      modal.onclick = (e) => {
        if (e.target.id === "rejectModalOverlay") {
          closeRejectModal();
        }
      };

      document.body.appendChild(modal);
    },

    // 处理宗亲荟成员审核
    processClanAudit(id, familyId, status, reason) {
      uni.showLoading({
        title: "处理中...",
      });

      const params = {
        id: id,
        status: status,
        reason: reason,
      };

      ClanMember.checkClanAudit(params)
        .then(() => {
          uni.hideLoading();
          uni.showToast({
            title: status === 1 ? "审核通过" : "已拒绝",
            icon: "success",
          });

          // 重新加载数据
          setTimeout(() => {
            this.onRefresh();
          }, 1000);
        })
        .catch((error) => {
          uni.hideLoading();
          uni.showToast({
            title: error.message || "审核失败",
            icon: "none",
          });
        });
    },
    // 根据分类获取标题字段
    getItemTitle(item) {
      if (this.currentCategory === "member") {
        return item.familyName || "未知家族";
      } else {
        // 宗亲荟成员审核
        return item.realName || item.name || item.nickname || item.familyName || "未知姓名";
      }
    },

    // 根据分类获取描述字段
    getItemDesc(item) {
      if (this.currentCategory === "member") {
        return item.nickname || "无";
      } else {
        // 宗亲荟成员审核
        return item.phone || item.mobile || item.description || "无";
      }
    },

    // 根据分类获取家族ID
    getItemFamilyId(item) {
      if (this.currentCategory === "member") {
        return item.familyId;
      } else {
        // 宗亲荟成员审核
        return item.familyId || item.clanId || item.clanFamilyId;
      }
    },
    loadMore() {
      if (this.currentCategory === "member") {
        if (this.memberNoMore || this.memberLoading) return;
        this.memberPageNum++;
        this.getMemberList(true);
      } else {
        if (this.clanNoMore || this.clanLoading) return;
        this.clanPageNum++;
        this.getClanList(true);
      }
    },
    onRefresh() {
      this.refreshing = true;
      this.resetPagination();
      this.loadData();
    },
    retryLoad() {
      this.loadError = false; // 隐藏错误状态
      this.loadData();
    },
  },
};
</script>
<style lang="scss">
.clan-member-item {
  .item-avatar {
    border-radius: 10px;
    margin-right: 4px;
  }

  .item-actions {
    display: flex !important;
    justify-content: space-between !important;
    margin-top: 4px !important;
  }
  .add-time {
    font-size: 12px;
    color: #999;
    background-color: #f9f9f9;
    padding: 2px 6px;
    border-radius: 10px;
  }
  .position-info {
    font-size: 14px;
    color: #999;
  }

  .position-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .position-tag {
    display: inline-block;
    background-color: #e8f4ff;
    color: #1890ff;
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 10px;
    line-height: 1.2;
    white-space: nowrap;
  }
  .company-info {
    font-size: 14px;
    color: #999;
  }
}

.avatar-img {
  width: 200rpx !important;
  height: 200rpx !important;
  border-radius: 10px;
}

.audit-list-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.category-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .tab-item {
    flex: 1;
    padding: 15px 0;
    text-align: center;
    font-size: 15px;
    color: #666;
    position: relative;
    transition: all 0.3s ease;

    &.active {
      color: #07c160;
      font-weight: bold;

      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background-color: #07c160;
        border-radius: 2px;
      }
    }

    &:active {
      background-color: #f5f5f5;
    }
  }
}

.filter-bar {
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .filter-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
    padding: 8px 15px;
    font-size: 14px;
    color: #333;
    background-color: #f5f5f5;
    border-radius: 20px;
  }
}

.item-content-wrapper {
  flex: 1;
}

.list-scroll {
  flex: 1;
  height: 0;
  padding: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;

  image {
    width: 100px;
    height: 100px;
    margin-bottom: 15px;
    opacity: 0.6;
  }

  text {
    font-size: 14px;
    color: #999;
  }
}

.initial-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 50px 0;
  text-align: center;
  font-size: 14px;
  color: #999;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;

  image {
    width: 100px;
    height: 100px;
    margin-bottom: 15px;
    opacity: 0.6;
  }

  text {
    font-size: 14px;
    color: #999;
    margin-bottom: 15px;
  }

  .retry-btn {
    width: 120px;
    height: 36px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    background-color: #07c160;
    border-radius: 20px;
    border: none;
  }
}

.list-item {
  margin-bottom: 12px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

  .item-content {
    display: flex;
    justify-content: space-between;
  }

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    .item-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .status-tag {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 10px;
      margin-left: 10px;

      &.status-0 {
        color: #ff9500;
        background-color: #fff8e6;
      }

      &.status-1 {
        color: #07c160;
        background-color: #e6f7ee;
      }

      &.status-2 {
        color: #ff4d4f;
        background-color: #fff1f0;
      }
    }
  }

  .item-content {
    display: flex;

    .item-desc {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      font-size: 14px;
      color: #666;
      margin-bottom: 10px;
      line-height: 1.5;
    }

    .item-meta {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: #999;
    }
  }

  .item-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;

    .action-btn {
      margin-left: 10px;
      font-size: 13px;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      margin-left: 0;
      margin-right: 0;
      &.pass {
        background-color: #07c160;
        color: white;
      }

      &.reject {
        background-color: #ff4d4f;
        color: white;
      }

      &.detail {
        background-color: #f0f0f0;
        color: #666;
      }
    }
  }

  /* 宗亲荟成员审核专用样式 - 图片靠左内容靠右布局 */
  .clan-member-item {
    display: flex;
    padding: 15px;

    .item-content-wrapper {
      flex: 1;
      min-width: 0;
      margin-right: 8px;
    }

    .item-avatar {
      flex: 0 0 auto;
      margin-right: 12px;

      .avatar-img {
        width: 48px !important;
        height: 48px !important;
        border-radius: 50%;
        background-color: #f5f5f5;
        border: 1px solid #eee;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
      }
    }

    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;

      .user-info {
        flex: 1;
        min-width: 0;

        .user-name {
          display: block;
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin-bottom: 3px;
          line-height: 1.2;
        }

        .job-title {
          display: inline-block;
          font-size: 11px;
          color: #1890ff;
          background-color: #e6f7ff;
          padding: 1px 6px;
          border-radius: 10px;
          border: 1px solid #91d5ff;
        }
      }
    }

    .company-info {
      margin-bottom: 8px;

      .company-name {
        display: block;
        font-size: 15px;
        color: #333;
        font-weight: 500;
        margin-bottom: 2px;
        line-height: 1.3;
      }

      .company-position {
        display: inline-block;
        font-size: 12px;
        color: #666;
        background-color: #f5f5f5;
        padding: 2px 8px;
        border-radius: 12px;
      }
    }

    .contact-info {
      margin-bottom: 6px;

      .phone {
        font-size: 14px;
        color: #07c160;
        font-weight: 500;
      }
    }

    .item-meta {
      margin-top: 8px;
    }

    .item-actions {
      flex: 0 0 auto;
      margin-top: 0;
      margin-left: 0;
      align-self: center;
      padding: 0 10px !important;
      .action-btn {
        min-width: 60px;
        height: 32px;
        line-height: 32px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 16px;
        padding: 0 12px;
      }
    }
  }
}

.loading-more,
.no-more {
  text-align: center;
  padding: 15px;
  font-size: 13px;
  color: #999;
}
</style>
